package controller;

import helper.Formatter;
import helper.Postman;
import helper.Randomness;
import helper.UserSession;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import databeans.Customer;
import databeans.Employee;
import model.EmployeeDAO;
import model.Model;

public class EmployeeCreateEmployeeAccountAction extends Action{
    private EmployeeDAO employeeDAO;

    public EmployeeCreateEmployeeAccountAction(Model model) {
        employeeDAO = model.getEmployeeDAO();
    }
    
    public String getName() {
        return "employeeCreateEmployeeAccount.do";
    }
    

    public String perform(HttpServletRequest request) {
        //ATTENTION
        // define target page
        //String loginPage = "employee/login-form.jsp";
        //String dashboardPage = "employee/employee-dashboard.jsp";
    
    	String loginPage = "employee/employee-login.jsp";
        String originPage = "employee/employee-manager.jsp";
    	//String originPage = "create-employee-acc.jsp";
        //String successPage = "create-employee-acc.jsp"; only for Ajax
        String successPage = originPage;
        
        //set the employee
        Employee employee = null;
        Customer customer = null;
        //errors and messages will be stored here
        //resetting those containers
        List<String> errors = new ArrayList<String>();
        List<String> messages = new ArrayList<String>();
   
        //define the error and message
        request.setAttribute("errors", errors);
        request.setAttribute("messages", messages);
        request.setAttribute("user-type", "employee");
        request.setAttribute("page", "create-emp");
        
        //get all the parameter from the form
        String requestType = request.getParameter("Submit");
        
        String username = request.getParameter("txtUsername");
        String firstName = request.getParameter("txtFirstName");
        String lastName = request.getParameter("txtLastName");
        String email = request.getParameter("txtEmail");
        //String password = request.getParameter("txtPassword");
        //String confirmPassword = request.getParameter("txtConfirmPassword");

        //reload the form field
        request.setAttribute("txtUsername", username);
        request.setAttribute("txtFirstName", firstName);
        request.setAttribute("txtLastName", lastName);
        request.setAttribute("txtEmail", email);
        
        //check if employee has been logged in
        //request.getSession() will return the current session and if one does not exist, a new session will be cretaed.
        //request.getSession(true) will return the current session if one exists, if one doesn't exits a new one will be created.
        //So there is actually no difference between the two methods HOWEVER, if you use request.getSession(false), it will return the current session if one exists and if one DOES NOT exist a new one will NOT be cretaed.
        employee = UserSession.getLoggedInEmployee(request);
        if (employee == null) {
            errors.add("You need to log in");
            request.setAttribute("page", "login");
            return loginPage ;
        }
        
        
        //check if customer has actually logged in
        customer = UserSession.getLoggedInCustomer(request);
        if (customer != null) {
            request = UserSession.removeCustomerFromSession(request);
            errors.add("This section is closed for customer");
            return loginPage;
        }


        // check for get or post request
        //if there is no parameter get passed, return to origin page
        if (requestType == null) {
            messages.add("To create employee account, fill the below form");
            return originPage;     
        }
        
        //validate the input
        if (firstName.trim().equals("")) {
            //messages.add("Enter customer first name");
            errors.add("First name cannot be blank. Please check.");
            return originPage;
        }
 
        if (lastName.trim().equals("")) {
            //messages.add("Enter customer last name");
            errors.add("Last name cannot be blank. Please check.");
            return originPage;
        }
        
        if (username.trim().equals("")) {
            //messages.add("Enter the desired username");
            errors.add("Username cannot be blank. Please check.");
            return originPage;
        }
        
        if (username.trim().length() < 4) {
            errors.add("Username entered is too short. Minimum length required is 8 characters.");
            return originPage;
        }
        
        if (email.trim().equals("")) {
            errors.add("Email cannot be blank. Please check.");
            return originPage;
        }
        
        if (username.trim().length() < 4){
            errors.add("Username must be 4 characters or more.");
            return originPage;
        }
        

        
        if (!Formatter.isEmail(email.trim())) {
            //messages.add("Email format must be *@*.*");
            errors.add("Invalid email address format. Please check.");
            return originPage;
        }
        
        
        
        /* Commented cos we will use random pass generator here
        if (password.trim().equals("")) {
            messages.add("Enter the desired password");
            errors.add("Current password field is still empty");
            return originPage;
        }

        if (confirmPassword.trim().equals("")){
            messages.add("Enter confirmation password");
            errors.add("Confirmation password field is still empty");
            return originPage;
        }
        
        if (!confirmPassword.trim().equals(password.trim())){
            messages.add("Both new password and confirmation password must be the same");
            errors.add("Both password and confirmation password you have supplied are different");
            return originPage;
        }
        */
        // Generate Random password

        
        // at this stage, all validation should have been done
        try {
            
            employee = employeeDAO.lookup(username);
            
            //check if employee username is unique
            if (employee!=null){
                errors.add("User already exist. Choose another username.");
                return originPage;
            }
             
            String randomPassword = "randomPassword";
            randomPassword = Randomness.randomPassword(8); 
            
            //create employee object
            employee = new Employee(username);
            employee.setFirstName(firstName);
            employee.setLastName(lastName);
            employee.setPassword(randomPassword);
            employee.setEmail(email);
            
            //create employee into database
            employeeDAO.create(employee);
            
            request.setAttribute("txtUsername", "");
            request.setAttribute("txtFirstName", "");
            request.setAttribute("txtLastName", "");
            request.setAttribute("txtEmail", "");
            
            // Attach (this copy of) the logged in employee bean to the session
            HttpSession session = request.getSession(true); 
            Employee loggedInEmployee = UserSession.getLoggedInEmployee(request);
            session = UserSession.setEmployeeIntoSession(request, loggedInEmployee);
            
            //email confirmation here
            //TODO activate this alter
            //Postman.sendCreateEmployeeConfirmation(employee, randomPassword);
            
          
            //set the progress
            //messages.add("Hi " + loggedInEmployee.getFirstName() + "!");
            messages.add("Succesfully crated employee with username: <b>" + employee.getUsername() + "</b> and password <b>" + randomPassword + "</b>");
            
            // Add email code here
            
            messages.add("Email confirmation has been sent to " + employee.getEmail());
            return successPage;

        } catch (Exception e) {
            errors.add("Unable to create new employee");
            return originPage;
        }

    }
}